package com.itboye.ihomebank.activity.keytwo;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.adapter.SheBeiTwoAdapter;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.SIDBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.KeyPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.JSONUtil;
import com.itboye.ihomebank.util.LoadingDialogTwo;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimesUtils;
import com.sitri.sdk.SLock;
import com.sitri.sdk.callback.visible.CommonCallback;
import com.sitri.sdk.callback.visible.InitBindCallback;
import com.sitri.sdk.callback.visible.SearchLocksCallback;
import com.sitri.sdk.model.ID;
import com.sitri.sdk.model.ResultData;
import com.sitri.sdk.model.ResultError;
import com.sitri.sdk.model.lock.UnlockRecord;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 白马云锁的附近设备
 */
public class SheBeiTwoActivity extends BaseOtherActivity implements CommonCallback ,Observer{
    View v_statusbar;
    ImageView close_icon;
    TextView add_shap_title_tv;
    SheBeiTwoAdapter adapter;
    ListView shebei_listview;

    LoadingDialogTwo loadingDialogTwo;

    List<String> listMac = new ArrayList<>();

    private KeyPresenter keyPresenter;
    String uid;
    String mac="";//当前mac
    ResultData resultData;

    @Override
    protected int layout_id() {
        return R.layout.activity_she_bei_two;
    }

    @Override
    protected void onInitController() {

    }
    @Override
    protected void onInit() {
        setStatusBarHeight(v_statusbar);
        add_shap_title_tv.setText("附近设备");
        keyPresenter=new KeyPresenter(this);
        uid = (String) SPUtils.get(MyApplcation.ctx, null, SPContants.USER_ID, "");
        SLock.getServices().setCommonCallback(this);
        loadingDialogTwo = new LoadingDialogTwo(this);
        SLock.getServices().startSearchLocks(5000, new SearchLocksCallback() {//搜索周边的白马云锁
            @Override
            public void onSearchStart() {
                showProgressDialog("正在搜索，请稍后......", false);
            }

            @Override
            public void onSearchResult(String mac, int rssi) {
                //mac需要去重
                if (!listMac.contains(mac)) {
                    listMac.add(mac);
                }
            }

            @Override
            public void onSearchEnd() {
                try {
                    closeProgressDialog();
                    adapter = new SheBeiTwoAdapter(SheBeiTwoActivity.this, listMac);
                    shebei_listview.setAdapter(adapter);
                } catch (Exception e) {
                }
            }
        });
        shebei_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    mac=listMac.get(position);
                    loadingDialogTwo.setMessage("正在绑定......").show();
                    SLock.getServices().initBindLock(listMac.get(position), "SLock", new InitBindCallback() {
                        @Override
                        public void onProgress(final int progress) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    loadingDialogTwo.setMessage("正在绑定......" + progress + "%");
                                    loadingDialogTwo.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                        @Override
                                        public void onDismiss(DialogInterface dialogInterface) {
                                            SLock.getServices().disconnectBle();
                                        }
                                    });
                                }
                            });
                        }
                    });
                }catch (Exception e){

                }

            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        SLock.getServices().disconnectBle();
    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_icon:
                finish();
                //  SLock.getServices().unBindLock("80eaca004023");
//                SLock.getServices().getUnlockRecords("80eaca004023", new UnlockRecordCallback() {
//                    @Override
//                    public void onResult(UnlockRecord record) {
//                        logUnlockRecord(record);
//
//                    }
//                });
                break;
            case R.id.add_shap_title_tv:
//                try {
//                    String sss=JSONUtil.fromList(list);
//                    ByAlert.alert(sss);
//
//                }catch (Throwable throwable) {
//                    throwable.printStackTrace();
//                }

                break;
            default:
                break;
        }
    }

    @Override
    public void onSuccess(ResultData resultData) {
        System.out.println("-----------------" + resultData.getData());
        log(resultData.getId(), true, resultData.getData());
        if (resultData.getId() == ID.INIT_BIND_LOCK) {
            this.resultData=resultData;
            if (loadingDialogTwo != null && loadingDialogTwo.isShowing()) {
                loadingDialogTwo.dismiss();
            }
            //白马锁绑定,保存mac地址，调用系统的初始化成功后清除掉。防止不同步
            SPUtils.put(MyApplcation.ctx, null,SPContants.BAIMA_LOCKMAC, mac);
            SPUtils.put(MyApplcation.ctx, null,SPContants.BAIMA_DATE, resultData.getData());

            showProgressDialog("正在绑定到服务器，请稍后......",false);
            String sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
            if("".equals(sid)){
                keyPresenter.initSitri(uid,mac,"Blelock","Blelock", TimesUtils.getStamp(),resultData.getData());
            }else {
                keyPresenter.initSitri(sid,mac,"Blelock","Blelock", TimesUtils.getStamp(),resultData.getData());

            }
        }
    }

    @Override
    public void onFailed(ResultError resultError) {
        System.out.println("===========" + resultError.getErrorCode().toLog());
        log(resultError.getId(), false, resultError.getErrorCode().toLog());
        if (loadingDialogTwo != null && loadingDialogTwo.isShowing()) {
            loadingDialogTwo.dismiss();
        }
    }

    private void log(ID id, boolean isSuccess, final String log) {
        if (isSuccess) {
          //  ByAlert.alert(id.name()+":第二个");
        } else {
            ByAlert.alert(TostKey.getStamp(log));
        }
    }

    private String getTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        return simpleDateFormat.format(new Date());
    }

    @Override
    public void update(Observable o, Object arg) {
        ResultEntity entity = handlerError(arg);
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
        if (entity != null) {
            if (!entity.getCode().equals(0)) {
                if (entity.getEventType() == KeyPresenter.initSitri_success) {
                    ByAlert.alert("绑定成功");
                    SPUtils.put(MyApplcation.ctx, null,SPContants.BAIMA_LOCKMAC,"");
                    Intent intent2 = new Intent("changeavart");
                    sendBroadcast(intent2);
                    finish();
                } else if (entity.getEventType() == KeyPresenter.initSitri_fail) {
                    if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                        //切换 锁备用服务器
                        showAlert();
                    }else {
                        ByAlert.alert(entity.getMsg());
                    }
                }else if (entity.getEventType()== UserPresenter.By_GETSID_success){//获取sid 成功
                    SIDBean data1 = (SIDBean) entity.getData();
                    SPUtils.put(MyApplcation.ctx,null, SPContants.LOCK_SESSION,data1.getSid());
                    SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
                    toRefreshData(data1.getSid());
                }else if (entity.getEventType()==UserPresenter.By_GETSID_fail){
                    ByAlert.alert(entity.getMsg());
                }
            }
        }
    }

    private void toRefreshData(String sid) {
        if ("".equals(sid)){
            keyPresenter.initSitri(uid,mac,"Blelock","Blelock", TimesUtils.getStamp(),resultData.getData());
        }else {
            keyPresenter.initSitri(sid,mac,"Blelock","Blelock", TimesUtils.getStamp(),resultData.getData());
        }

    }

    List<String> list=new ArrayList<>();
    private void logUnlockRecord(UnlockRecord record) {
        JSONObject object = record.toJSONObject();

     final   String   str = object.toString();
        list.add(str);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ByAlert.alert(str);
            }
        });
    }
}
